package com.codi.bus.core.service.organ.impl;

import com.codi.base.exception.BaseAppException;
import com.codi.base.util.DateUtils;
import com.codi.base.util.MoneyUtils;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.dao.*;
import com.codi.bus.core.domain.*;
import com.codi.bus.core.resultModel.*;
import com.codi.bus.core.service.*;
import com.codi.bus.core.service.model.ApplyModel;
import com.codi.bus.core.service.model.FundModel;
import com.codi.bus.core.service.model.NewsModel;
import com.codi.bus.core.service.model.ShareModel;
import com.codi.bus.core.service.organ.OrganBankService;
import com.codi.bus.core.service.organ.OrganLocalAssetsService;
import com.codi.bus.core.service.util.CalculateAssetsUtils;
import com.codi.bus.core.service.util.HundsunUtils;
import com.codi.bus.core.service.util.ModelPopulateUtils;
import com.codi.bus.exception.BaseException;
import com.codi.fundData.domain.FundMMYieldPerformance;
import com.codi.fundData.domain.SecurityProduct;
import com.codi.fundData.service.FundMMYieldPerformanceService;
import com.codi.message.constant.ErrorConstant;
import com.codi.message.util.MessageUtil;
import com.codi.trade.service.TradeApplyQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2018/6/22.
 */
@Service("organLocalAssetsService")
@Slf4j
public class OrganLocalAssetsServiceImpl implements OrganLocalAssetsService {

    @Autowired
    private UserService userService;

    @Autowired
    private LookupDao lookupDao;

    @Autowired
    private ProfitDao profitDao;

    @Autowired
    private OrganProfileDao organProfileDao;

    @Autowired
    private FundDividentsDao fundDividentsDao;

    @Autowired
    private OrganBankService organBankService;

    @Autowired
    private QueryService queryService;

    @Autowired
    private FundDetailService fundDetailService;

    @Autowired
    private CdUserShareDao cdUserShareDao;

    @Autowired
    private TradeApplyQueryService tradeApplyQueryService;

    @Autowired
    private FundMMYieldPerformanceService fundMMYieldPerformanceService;

    @Autowired
    private FundCombinationMappingDao fundCombinationMappingDao;

    @Autowired
    private LocalAssetsService localAssetsService;

    @Autowired
    private ProfitService profitService;


    /**
     * 获取 基金资产列表
     *
     * @param userId
     * @param requestNum
     * @param beginNum
     * @return
     * @throws BaseException
     * @throws BaseAppException
     */
    @Override
    public ShareListResult getAllShares(Long userId, Long profileId, Integer requestNum, Integer beginNum) throws BaseException, BaseAppException {
        User user = userService.getUser(userId);
        //需要传机构的clientId 来获取 收益
        OrganProfile organProfile = organProfileDao.qryByProfileId(profileId);
        ShareListResult result = new ShareListResult();
        // 判断是否已开户
        if (user == null || StringUtil.isEmpty(organProfile.getExternalClientId())) {
            result.setErrorCode(ErrorConstant.ERROR_NO_ACCOUNT);
            result.setSuccess(false);
            result.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
            return result;
        }
        Date netValueDate = DateUtils.addDay(new Date(), -1); //默认净值日期为前一天

        // 总持仓收益
        BigDecimal totalAccumIncome = new BigDecimal(0);
        log.debug("totalAccumIncome1:{}", totalAccumIncome);

        // 总本金
        BigDecimal totalFundBalance = new BigDecimal(0);
        // 总资产
        BigDecimal totalWorthValue = new BigDecimal(0);
        // 总当日收益
        BigDecimal totalTodayIncome = new BigDecimal(0);
        //总持仓收益
        BigDecimal totalShareIncome = new BigDecimal(0);

        /**
         * 交易记录
         */
        // 查出这个用户下所有的未确认的交易记录，传ClientId
        Map<String, Object> map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
            organProfile.getExternalClientId(), "", "", "", GlobalConstant.TACONFIRM_FLAG_UNCONFIRM, "", "", "", "", "",
            "", "", "");

        // 查询结果
        List<Map<String, Object>> list = new ArrayList<>();
        HundsunUtils.ConvertToList(map, list, result);
        if (!result.getSuccess()) {
            return result;
        }
        // populate applys
        ApplyListResult applyListResult = new ApplyListResult();
        List<ApplyModel> applys = ModelPopulateUtils.populateApply(list, applyListResult, null, null);
        // 把T0基金过滤掉，因为T0基金有专门的页面来显示
        queryService.filterOrganBao(applys);
        // 获取T+0基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);


        List<Profit> profitList = profitService.getUserNewProfit(userId.intValue(), organProfile.getExternalClientId());
        List<FundDividents> fundDividents = fundDividentsDao.selectDividend(userId.intValue(), organProfile.getExternalClientId(), null, null);
        List<ShareModel> normalShares = new ArrayList<>();
        for (Profit profit : profitList) {
            if (profit.getTradeAcco().startsWith("ZH") || CalculateAssetsUtils.isT0Fund(lookups, profit.getFundCode())) {
                continue;
            }
            ShareModel shareModel = new ShareModel();
            shareModel.setFundCode(profit.getFundCode());
            OrganBank organBank = organBankService.selectByTradeAccount(profit.getTradeAcco());
            if (organBank != null) {
                shareModel.setBranchBank(organBank.getUbBranchbank());
                shareModel.setBranchBankName(organBank.getUbBankBranchName());
                shareModel.setBankCode(organBank.getUbBankCode());
            }

            shareModel.setTradeAccount(profit.getTradeAcco());
            shareModel.setNetValue(profit.getNetValue());
            FundNetValueResult fundNetValue = fundDetailService.getFundNetValue(profit.getFundCode(), DateUtils.stringToDateWithTime(profit.getCreateTime()));
            shareModel.setFundName(fundNetValue.getChiNameAbbr());
            shareModel.setNetValueDate(fundNetValue.getTradingDay());
            netValueDate = fundNetValue.getTradingDay();
            // 设置前端显示的基金类型
            shareModel.setAppFundType(fundNetValue.getFundTypeCode());
            shareModel.setDailyProfit(fundNetValue.getDailyProfit());
            shareModel.setTodayIncomeRate(fundNetValue.getNvDailyGrowthRate());
            shareModel.setCurrentShare(profit.getShares());
            BigDecimal todayIncome = profit.getProfitValue();
            BigDecimal totalDividend = new BigDecimal(0);
            for (FundDividents dividendModel : fundDividents) {
                if ("1".equals(dividendModel.getAutoBuy()) && dividendModel.getTradeAcco().equals(shareModel.getTradeAccount()) && dividendModel.getFundCode().equals(shareModel.getFundCode())) {
                    if (dividendModel.getDividendDate().equals(DateUtils.formatDate4(DateUtils.addDay(new Date(), -1)))) {
                        todayIncome = MoneyUtils.add(todayIncome, dividendModel.getDividendBala());
                    }
                    if (dividendModel.getDividendDate().compareTo(DateUtils.formatDate4(new Date())) < 0) {
                        totalDividend = MoneyUtils.add(totalDividend, dividendModel.getDividendBala());
                    }
                    if (DateUtils.formatDate4(new Date()).compareTo(dividendModel.getEquityRegDate()) >= 0 && DateUtils.formatDate4(new Date()).compareTo(dividendModel.getDividendDate()) <= 0) {
                        shareModel.setDividends("该基金最近有分红配送");
                    }
                }

            }
            if (shareModel.getDividends() == null) {
                shareModel.setDividends("");
            }
            todayIncome = todayIncome.setScale(2, BigDecimal.ROUND_HALF_UP);
            shareModel.setTodayIncome(todayIncome);
            List<CdUserShare> cdUserShares = cdUserShareDao.selectNewShare(userId.intValue(), organProfile.getExternalClientId(), shareModel.getTradeAccount(), profit.getFundCode());
            BigDecimal unpaidIncome = new BigDecimal(0);
            if (!cdUserShares.isEmpty()) {
                unpaidIncome = cdUserShares.get(0).getUnpaidIncome();
                shareModel.setEnableShares(cdUserShares.get(0).getEnableShares());
                shareModel.setShareType(cdUserShares.get(0).getShareType());
                shareModel.setAutoBuy(cdUserShares.get(0).getAutoBuy());
                shareModel.setCapitalMode(cdUserShares.get(0).getCapitalMode());
                shareModel.setBankAccount(cdUserShares.get(0).getBankAccount());
                // 根据恒生银行编号获取银行名称
                List<Lookup> lookupsBank = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_EPAYBANK);
                if (lookupsBank != null) {
                    for (Lookup lookup : lookupsBank) {
                        if (lookup.getRuleValue().equals(shareModel.getBankCode())) {
                            shareModel.setBankName(lookup.getRuleText());
                            break;
                        }
                    }
                }
            }
            BigDecimal worthValue = shareModel.getEnableShares().multiply(shareModel.getNetValue());
            worthValue = MoneyUtils.add(worthValue, unpaidIncome);
            shareModel.setWorthValue(worthValue);
            //如果是 货币基金 要减去昨日收益  因为货币基金的资产到的迟  所以要和资产同步展示  如果收益日期不是 前一天就不需要减去
            if (shareModel.getAppFundType() == GlobalConstant.CURRENCY_APP_FUND_TYPE_ONE || shareModel.getAppFundType() == GlobalConstant.CURRENCY_APP_FUND_TYPE_TWO) {
                shareModel.setTotalAccumIncome(MoneyUtils.subtract(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend), todayIncome));
//                if (DateUtils.formatDate(DateUtils.addDay(new Date(), -1)).equals(profit.getDateTime())) {
//                    shareModel.setTotalAccumIncome(MoneyUtils.subtract(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend), todayIncome));
//                } else {
//                    shareModel.setTotalAccumIncome(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend));
//                }
            } else {
                shareModel.setTotalAccumIncome(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend));
            }

            totalAccumIncome = MoneyUtils.add(shareModel.getTotalAccumIncome(), totalAccumIncome);

            Integer sellInTransit = CalculateAssetsUtils.numSellOfInTransit(applys, lookups, false, shareModel.getFundCode(), shareModel.getTradeAccount());
            shareModel.setSellInTransit(sellInTransit);

            shareModel.setClearDate(fundNetValue.getCarryOverDateRemark());
            totalWorthValue = totalWorthValue.add(shareModel.getWorthValue());
            totalTodayIncome = totalTodayIncome.add(shareModel.getTodayIncome());
            shareModel.setLatestWeeklyYield("");
            normalShares.add(shareModel);
        }
        BigDecimal totalInTransit = new BigDecimal(0);
        Integer numInTransit = CalculateAssetsUtils.numOfInTransitWithoutPortfolio(applys, lookups, null);
        totalInTransit = CalculateAssetsUtils.sumOfInTransitWithoutPortfolio(applys, lookups, null);
        totalWorthValue = MoneyUtils.add(totalWorthValue, totalInTransit);

        List<ShareModel> normalSharesNew = localAssetsService.getShareModel(normalShares, null);
        List<ShareModel> normalSharesReal = new ArrayList<>();
        for (int i = 1; i <= normalSharesNew.size(); i++) {
            if (i >= beginNum && i < requestNum + beginNum) {
                normalSharesReal.add(normalSharesNew.get(i - 1));
            }
        }
        result.setSuccess(true);
        result.setShares(normalSharesReal);
        result.setNetValueDate(netValueDate);
        result.setTotalInTransit(totalInTransit);
        result.setTotalNumInTransit(numInTransit);
        result.setTotalAccumIncome(totalAccumIncome);
        result.setTotalFundBalance(totalFundBalance);
        result.setTotalTodayIncome(totalTodayIncome);
        result.setTotalShareIncome(totalShareIncome);
        result.setTotalWorthValue(totalWorthValue);

        return result;
    }

    /**
     * 获取 企业宝资产列表
     *
     * @param userId
     * @param requestNum
     * @param beginNum
     * @return
     * @throws BaseException
     * @throws BaseAppException
     */
    @Override
    public ShareListResult getAllOrganBao(Long userId, Long profileId, Integer requestNum, Integer beginNum) throws BaseException, BaseAppException {
        User user = userService.getUser(userId);
        //需要传机构的clientId 来获取 收益
        OrganProfile organProfile = organProfileDao.qryByProfileId(profileId);
        ShareListResult result = new ShareListResult();
        // 判断是否已开户
        if (user == null || StringUtil.isEmpty(organProfile.getExternalClientId())) {
            result.setErrorCode(ErrorConstant.ERROR_NO_ACCOUNT);
            result.setSuccess(false);
            result.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
            return result;
        }
        Date netValueDate = DateUtils.addDay(new Date(), -1); //默认净值日期为前一天

        // 总持仓收益
        BigDecimal totalAccumIncome = new BigDecimal(0);
        log.debug("totalAccumIncome1:{}", totalAccumIncome);

        // 总本金
        BigDecimal totalFundBalance = new BigDecimal(0);
        // 总资产
        BigDecimal totalWorthValue = new BigDecimal(0);
        // 总当日收益
        BigDecimal totalTodayIncome = new BigDecimal(0);
        //总持仓收益
        BigDecimal totalShareIncome = new BigDecimal(0);

        /**
         * 交易记录
         */
        // 查出这个用户下所有的未确认的交易记录，传ClientId
        Map<String, Object> map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
            organProfile.getExternalClientId(), "", "", "", GlobalConstant.TACONFIRM_FLAG_UNCONFIRM, "", "", "", "", "",
            "", "", "");

        // 查询结果
        List<Map<String, Object>> list = new ArrayList<>();
        HundsunUtils.ConvertToList(map, list, result);
        if (!result.getSuccess()) {
            return result;
        }
        // populate applys
        ApplyListResult applyListResult = new ApplyListResult();
        List<ApplyModel> applys = ModelPopulateUtils.populateApply(list, applyListResult, null, null);
        // 把T0基金过滤掉，因为T0基金有专门的页面来显示
        queryService.getOrganBao(applys);
        // 获取T+0基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);


        List<Profit> profitList = profitService.getUserNewProfit(userId.intValue(), organProfile.getExternalClientId());
        //List<FundDividents> fundDividents = fundDividentsDao.selectDividend(userId.intValue(), organProfile.getExternalClientId(), null, null);
        List<ShareModel> normalShares = new ArrayList<>();
        for (Profit profit : profitList) {
            if (profit.getTradeAcco().startsWith("ZH") || !CalculateAssetsUtils.isT0Fund(lookups, profit.getFundCode())) {
                continue;
            }
            ShareModel shareModel = new ShareModel();
            shareModel.setFundCode(profit.getFundCode());
            OrganBank organBank = organBankService.selectByTradeAccount(profit.getTradeAcco());
            if (organBank != null) {
                shareModel.setBranchBank(organBank.getUbBranchbank());
                shareModel.setBranchBankName(organBank.getUbBankBranchName());
                shareModel.setBankCode(organBank.getUbBankCode());
            }

            shareModel.setTradeAccount(profit.getTradeAcco());
            shareModel.setNetValue(profit.getNetValue());
            FundNetValueResult fundNetValue = fundDetailService.getFundNetValue(profit.getFundCode(), DateUtils.stringToDateWithTime(profit.getCreateTime()));
            shareModel.setFundName(fundNetValue.getChiNameAbbr());
            shareModel.setNetValueDate(fundNetValue.getTradingDay());
            netValueDate = fundNetValue.getTradingDay();
            // 设置前端显示的基金类型
            shareModel.setAppFundType(fundNetValue.getFundTypeCode());
            shareModel.setDailyProfit(fundNetValue.getDailyProfit());
            shareModel.setTodayIncomeRate(fundNetValue.getNvDailyGrowthRate());
            shareModel.setCurrentShare(profit.getShares());
            BigDecimal todayIncome = profit.getProfitValue();

            if (shareModel.getDividends() == null) {
                shareModel.setDividends("");
            }
            todayIncome = todayIncome.setScale(2, BigDecimal.ROUND_HALF_UP);
            shareModel.setTodayIncome(todayIncome);
            List<CdUserShare> cdUserShares = cdUserShareDao.selectNewShare(userId.intValue(), organProfile.getExternalClientId(), shareModel.getTradeAccount(), profit.getFundCode());
            BigDecimal unpaidIncome = new BigDecimal(0);
            if (!cdUserShares.isEmpty()) {
                unpaidIncome = cdUserShares.get(0).getUnpaidIncome();
                shareModel.setEnableShares(cdUserShares.get(0).getEnableShares());
                shareModel.setShareType(cdUserShares.get(0).getShareType());
                shareModel.setAutoBuy(cdUserShares.get(0).getAutoBuy());
                shareModel.setBankAccount(cdUserShares.get(0).getBankAccount());
                shareModel.setCapitalMode(cdUserShares.get(0).getCapitalMode());
                // 根据恒生银行编号获取银行名称
                List<Lookup> lookupsBank = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_EPAYBANK);
                if (lookupsBank != null) {
                    for (Lookup lookup : lookupsBank) {
                        if (lookup.getRuleValue().equals(shareModel.getBankCode())) {
                            shareModel.setBankName(lookup.getRuleText());
                            break;
                        }
                    }
                }
            }
            BigDecimal worthValue = shareModel.getEnableShares().multiply(shareModel.getNetValue());
            worthValue = MoneyUtils.add(worthValue, unpaidIncome);
            shareModel.setWorthValue(worthValue);
            shareModel.setTotalAccumIncome(MoneyUtils.subtract(profit.getAccumulateProfitValue(), todayIncome));
            //如果收益日期不是 前一天就不需要减去
//            if (DateUtils.formatDate(DateUtils.addDay(new Date(), -1)).equals(profit.getDateTime())) {
//                shareModel.setTotalAccumIncome(MoneyUtils.subtract(profit.getAccumulateProfitValue(), todayIncome));
//            } else {
//            shareModel.setTotalAccumIncome(profit.getAccumulateProfitValue());
//        }


            totalAccumIncome = MoneyUtils.add(shareModel.getTotalAccumIncome(), totalAccumIncome);

            Integer sellInTransit = CalculateAssetsUtils.numSellOfInTransit(applys, lookups, true, shareModel.getFundCode(), shareModel.getTradeAccount());
            shareModel.setSellInTransit(sellInTransit);

            shareModel.setClearDate(fundNetValue.getCarryOverDateRemark());
            totalWorthValue = totalWorthValue.add(shareModel.getWorthValue());
            totalTodayIncome = totalTodayIncome.add(shareModel.getTodayIncome());
            shareModel.setLatestWeeklyYield("");
            normalShares.add(shareModel);
        }
        BigDecimal totalInTransit = new BigDecimal(0);
        Integer numInTransit = CalculateAssetsUtils.numOfInTransit(applys, lookups, true, null, null);
        totalInTransit = CalculateAssetsUtils.sumOfInTransit(applys, lookups, true, null, null);
        totalWorthValue = MoneyUtils.add(totalWorthValue, totalInTransit);

        List<ShareModel> normalSharesNew = localAssetsService.getShareModel(normalShares, null);
        List<ShareModel> normalSharesReal = new ArrayList<>();
        for (int i = 1; i <= normalSharesNew.size(); i++) {
            if (i >= beginNum && i < requestNum + beginNum) {
                normalSharesReal.add(normalSharesNew.get(i - 1));
            }
        }
        result.setSuccess(true);
        result.setShares(normalSharesReal);
        result.setNetValueDate(netValueDate);
        result.setTotalInTransit(totalInTransit);
        result.setTotalNumInTransit(numInTransit);
        result.setTotalAccumIncome(totalAccumIncome);
        result.setTotalFundBalance(totalFundBalance);
        result.setTotalTodayIncome(totalTodayIncome);
        result.setTotalShareIncome(totalShareIncome);
        result.setTotalWorthValue(totalWorthValue);

        return result;
    }

    // 获取单个基金资产
    @Override
    public BaseResult getFundShares(Long userId, String fundCode, Long profileId) throws BaseAppException {
        User user = userService.getUser(userId);
        BaseResult result = new BaseResult();

        Date netValueDate = DateUtils.addDay(new Date(), -1); //默认净值日期为前一天

        //需要传机构的clientId 来获取 收益
        OrganProfile organProfile = organProfileDao.qryByProfileId(profileId);
        List<Profit> profitList = profitDao.selectNewProfit(userId.intValue(), organProfile.getExternalClientId(), null, fundCode);

        List<FundDividents> fundDividents = fundDividentsDao.selectDividend(userId.intValue(), organProfile.getExternalClientId(), null, fundCode);
        List<ShareModel> normalShares = new ArrayList<>();
        FundModel fundModel = queryService.queryFund(fundCode);
        for (Profit profit : profitList) {
            if (profit.getTradeAcco().startsWith("ZH")) {
                continue;
            }
            ShareModel shareModel = new ShareModel();
            shareModel.setFundCode(fundCode);
            OrganBank organBank = organBankService.selectByTradeAccount(profit.getTradeAcco());
            if (organBank != null) {
                shareModel.setBranchBank(organBank.getUbBranchbank());
                shareModel.setBranchBankName(organBank.getUbBankBranchName());
                shareModel.setBankCode(organBank.getUbBankCode());
            }

            shareModel.setFundStatus(fundModel.getFundStatus());
            shareModel.setTradeAccount(profit.getTradeAcco());
            shareModel.setNetValue(profit.getNetValue());
            FundNetValueResult fundNetValue = fundDetailService.getFundNetValue(fundCode, DateUtils.stringToDateWithTime(profit.getCreateTime()));
            shareModel.setFundName(fundNetValue.getChiNameAbbr());
            shareModel.setNetValueDate(fundNetValue.getTradingDay());
            netValueDate = fundNetValue.getTradingDay();
            // 设置前端显示的基金类型
            shareModel.setAppFundType(fundNetValue.getFundTypeCode());
            shareModel.setDailyProfit(fundNetValue.getDailyProfit());
            shareModel.setTodayIncomeRate(fundNetValue.getNvDailyGrowthRate());
            shareModel.setCurrentShare(profit.getShares());
            BigDecimal todayIncome = profit.getProfitValue();
            BigDecimal totalDividend = new BigDecimal(0);
            for (FundDividents dividendModel : fundDividents) {
                if ("1".equals(dividendModel.getAutoBuy()) && dividendModel.getTradeAcco().equals(shareModel.getTradeAccount())) {
                    if (dividendModel.getDividendDate().equals(DateUtils.formatDate4(DateUtils.addDay(new Date(), -1)))) {
                        todayIncome = MoneyUtils.add(todayIncome, dividendModel.getDividendBala());
                    }
                    if (dividendModel.getDividendDate().compareTo(DateUtils.formatDate4(new Date())) < 0) {
                        totalDividend = MoneyUtils.add(totalDividend, dividendModel.getDividendBala());
                    }
                    if (DateUtils.formatDate4(new Date()).compareTo(dividendModel.getEquityRegDate()) >= 0 && DateUtils.formatDate4(new Date()).compareTo(dividendModel.getDividendDate()) <= 0) {
                        shareModel.setDividends("该基金最近有分红配送");
                    }
                }

            }
            if (shareModel.getDividends() == null) {
                shareModel.setDividends("");
            }
            todayIncome = todayIncome.setScale(2, BigDecimal.ROUND_HALF_UP);
            shareModel.setTodayIncome(todayIncome);
            List<CdUserShare> cdUserShares = cdUserShareDao.selectNewShare(userId.intValue(), organProfile.getExternalClientId(), shareModel.getTradeAccount(), fundCode);
            BigDecimal unpaidIncome = new BigDecimal(0);
            if (!cdUserShares.isEmpty()) {
                unpaidIncome = cdUserShares.get(0).getUnpaidIncome();
                shareModel.setEnableShares(cdUserShares.get(0).getEnableShares());
                shareModel.setShareType(cdUserShares.get(0).getShareType());
                shareModel.setCapitalMode(cdUserShares.get(0).getCapitalMode());
                shareModel.setAutoBuy(cdUserShares.get(0).getAutoBuy());
                shareModel.setBankAccount(cdUserShares.get(0).getBankAccount());
                // 根据恒生银行编号获取银行名称
                List<Lookup> lookupsBank = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_EPAYBANK);
                if (lookupsBank != null) {
                    for (Lookup lookup : lookupsBank) {
//                        if (GlobalConstant.ABC.equals(shareModel.getBankCode())){
//
//                        }
                        if (lookup.getRuleValue().equals(shareModel.getBankCode())) {
                            shareModel.setBankName(lookup.getRuleText());
                            break;
                        }
                    }
                }
            }
            BigDecimal worthValue = shareModel.getEnableShares().multiply(shareModel.getNetValue());
            worthValue = MoneyUtils.add(worthValue, unpaidIncome);
            shareModel.setWorthValue(worthValue);
            //如果是 货币基金 要减去昨日收益  因为货币基金的资产到的迟  所以要和资产同步展示  如果收益日期不是 前一天就不需要减去
            if (shareModel.getAppFundType() == GlobalConstant.CURRENCY_APP_FUND_TYPE_ONE || shareModel.getAppFundType() == GlobalConstant.CURRENCY_APP_FUND_TYPE_TWO) {
                shareModel.setTotalAccumIncome(MoneyUtils.subtract(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend), todayIncome));
//                if (DateUtils.formatDate(DateUtils.addDay(new Date(), -1)).equals(profit.getDateTime())) {
//                    shareModel.setTotalAccumIncome(MoneyUtils.subtract(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend), todayIncome));
//                } else {
//                    shareModel.setTotalAccumIncome(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend));
//                }
            } else {
                shareModel.setTotalAccumIncome(MoneyUtils.add(profit.getAccumulateProfitValue(), totalDividend));
            }
            /**
             * 交易记录
             */
            // 查出这个用户下所有的未确认的交易记录，传ClientId
            Map<String, Object> map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
                organProfile.getExternalClientId(), "", "", "", GlobalConstant.TACONFIRM_FLAG_UNCONFIRM, "", "", "", "", "",
                "", "", "");

            // 查询结果
            List<Map<String, Object>> list = new ArrayList<>();
            HundsunUtils.ConvertToList(map, list, result);
            if (!result.getSuccess()) {
                return result;
            }
            // populate applys
            ApplyListResult applyListResult = new ApplyListResult();
            List<ApplyModel> applys = ModelPopulateUtils.populateApply(list, applyListResult, null, null);
            // 把企业宝基金过滤掉，因为T0基金有专门的页面来显示
//            queryService.filterOrganBao(applys);
            Integer sellInTransit = CalculateAssetsUtils.organNumSellOfInTransit(applys, shareModel.getFundCode(), shareModel.getTradeAccount());
            shareModel.setSellInTransit(sellInTransit);
            // 获取基金类型
            NewsModel newsModel = queryService.getRiskLevel(shareModel.getFundCode());
            if (newsModel != null) {
                shareModel.setFundType(newsModel.getFundType());
                shareModel.setRiskLevel(newsModel.getRiskLevel());
                shareModel.setRiskLevelString(newsModel.getRiskLevelString());
            }

            shareModel.setClearDate(fundNetValue.getCarryOverDateRemark());
            SecurityProduct product = fundDetailService.getSecurityProduct(shareModel.getFundCode());

            if (product == null) {
                log.error("Security Product is not exist");
                result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
                result.setErrorCode(ErrorConstant.ERROR_FUND_NOT_EXIST);
                result.setSuccess(false);
                return result;
            }

            // 七日年化率
            FundMMYieldPerformance perf = fundMMYieldPerformanceService.getFundMMYieldPerformance(product.getInnerCode());
            if (perf != null && perf.getLatestWeeklyYield() != null) {
                shareModel.setLatestWeeklyYield(MoneyUtils.formatMoney(perf.getLatestWeeklyYield(), 2));// 最近7日折算年收益率（%）
            } else {
                shareModel.setLatestWeeklyYield("");
            }

            shareModel.setCanDividend(true);
            if (shareModel.getAppFundType() == 900000 || shareModel.getAppFundType() == 1109) {
                shareModel.setCanDividend(false);
                shareModel.setDividendMethodString("当前基金仅支持红利再投资");
            }
            normalShares.add(shareModel);
        }

        List<ShareModel> normalSharesNew = localAssetsService.getShareModel(normalShares, fundCode);

        result.setSuccess(true);
        result.setResult(normalSharesNew);

        return result;
    }

    /**
     * 机构全部资产
     *
     * @param userId
     * @param profileId
     * @return
     */
    @Override
    public AssetsResult getOrganAssets(Long userId, Long profileId) {
        AssetsResult assetsResult = new AssetsResult();
        // 企业宝
        ShareListResult allOrganBao = new ShareListResult();
        try {
            allOrganBao = getAllOrganBao(userId, profileId, GlobalConstant.MAX_REQUEST_NUM, 0);
        } catch (BaseAppException e) {
            e.printStackTrace();
        }
        BigDecimal walletInTransitAmount = allOrganBao.getTotalInTransit();
        BigDecimal walletTotalTodayIncome = allOrganBao.getTotalTodayIncome();
        BigDecimal walletTotalAccumIncome = allOrganBao.getTotalAccumIncome();
        BigDecimal walletTotalWorthValue = allOrganBao.getTotalWorthValue();


        // 计算普通基金
        try {
            ShareListResult allShares = getAllShares(userId, profileId, GlobalConstant.MAX_REQUEST_NUM, 0);
            localAssetsService.getNormalAssets(assetsResult, allShares);
        } catch (BaseAppException e) {
            e.printStackTrace();
        }

        BigDecimal fundTotalAccumIncome = assetsResult.getFund().getTotalAccumIncome();
        assetsResult.setTotalAccumIncome(MoneyUtils.add(walletTotalAccumIncome, fundTotalAccumIncome));

        BigDecimal fundTotalWorthValue = assetsResult.getFund().getTotalWorthValue();
        assetsResult.setTotalWorthValue(MoneyUtils.add(walletTotalWorthValue, fundTotalWorthValue));

        BigDecimal fundTodayIncome = assetsResult.getFund().getTotalTodayIncome();
        assetsResult.setTotalTodayIncome(MoneyUtils.add(fundTodayIncome, walletTotalTodayIncome));

        BigDecimal fundInTransitAmount = assetsResult.getFund().getInTransitAmount();
        assetsResult.setTotalInTransitAmount(MoneyUtils.add(walletInTransitAmount, fundInTransitAmount));
        assetsResult.setTotalInTransitNum(assetsResult.getFund().getInTransitNum() + allOrganBao.getTotalNumInTransit());

        return assetsResult;
    }
}
